# -*- coding:UTF-8 -*-
import time

import pymongo
import json


from flask import send_file, Blueprint

from db import *
from flask import request, render_template
from spider_nga.content import search_content_1

path = "/home/yk/kapp/stockList.json"

record = Blueprint("record", __name__)



@record.route('/search')
def search1():
    # print(request.args)
    search = request.args.get('key')
    detail = request.args.get('detail')
    ret = seach(search, detail)
    # print(ret)
    # data = json.dumps(ret, sort_keys=True, indent=2)
    # data = data.encode('utf-8').decode('unicode_escape')
    # print(data)
    return render_template("tmp.html", mydict=ret, keyl=search)

@record.route('/')
def index():
    return render_template("index.html")


@record.route('/name')
def search2():
    search = request.args.get('key')
    ret = seachName(search)
    return render_template("tmp2.html", md=ret, keyl=search)



@record.route('/content')
def search_content():
    search = request.args.get('key')
    print(search, 222222222222)
    ret = search_content_1(search)
    return render_template("tmp3.html", md=ret, keyl=search)


def seachName(target):
    stockList = loadJson(path)
    printStock = search(target, stockList)
    return printStock



def loadJson(path):
    with open(path, 'r') as f:
        stockList = json.load(f)
        return stockList
      

def search(target, stockList):
    targetLen = len(target)
    all = [target]
    if targetLen > 5 or targetLen < 2:
        print("cao")
    elif targetLen == 3:
        for i in range(0, targetLen-1):
            all.append(target[i: i+2])
    elif targetLen == 4:
        for i in range(0, targetLen - 2):
            all.append(target[i: i + 3])

        for i in range(0, targetLen - 1):
            all.append(target[i: i + 2])
    printStock = {}
    already = []
    for stock in stockList:
        for strPeace in all:
            if strPeace not in printStock:
                printStock[strPeace] = []
            if strPeace in stock["alpha"].lower():
                if stock not in already:
                    printStock[strPeace].append(stock)
                    already.append(stock)

    return printStock